package me.ezitku.base.extensions.phone

import android.content.Context
import android.content.Context.TELEPHONY_SERVICE
import android.telephony.PhoneStateListener
import android.telephony.TelephonyManager

/**
 * تېلفۇن كەلگەننى ،سۆلىشىش ئۈزۈلگەن ، سۆزلىشىش باشلانغاننى باشقۇرۇش
 */
fun Context.phoneCallListener(action: _PhoneStateListener.() -> Unit) {
    var telphone = getSystemService(TELEPHONY_SERVICE) as TelephonyManager
    telphone.listen(_PhoneStateListener().apply(action), PhoneStateListener.LISTEN_CALL_STATE)
}

class _PhoneStateListener : PhoneStateListener() {
    private var _ringing: ((incomingNumber: String) -> Unit)? = null//تېلفۇن كەلگەندە
    private var _offHook: (() -> Unit)? = null//تېلفۇن سۆزلىشىش باشلانغاندا
    private var _idle: (() -> Unit)? = null//تېلفۇن سۆزلىشىش ئاخىرلاشقاندا
    override fun onCallStateChanged(state: Int, incomingNumber: String?) {
        super.onCallStateChanged(state, incomingNumber)
        when (state) {
            TelephonyManager.CALL_STATE_RINGING -> {
                _ringing?.invoke(incomingNumber!!)
            }
            TelephonyManager.CALL_STATE_OFFHOOK -> {
                _offHook?.invoke()
            }
            TelephonyManager.CALL_STATE_IDLE -> {
                _idle?.invoke()
            }
        }
    }

    fun تېلفۇن_كەلدى(ringing: (incomingNumber: String) -> Unit) {
        _ringing = ringing
    }

    fun تېلفۇن_سۆزلىشىش_باشلاندى(offHook: () -> Unit) {
        _offHook = offHook
    }

    fun تېلفۇن_سۆزلىشىش_تامام(idle: () -> Unit) {
        _idle = idle
    }

}